<?php
namespace app\web\controller;

use think\Controller;

/**
 * 后台登录
 * @author Kaisa
 * @version 2017-02-11
 */
class LoginController extends Controller {
    /**
     * 后台登录
     * @return mixed
     */
    public function index() {
   
    	// 已登录直接登录
    	if (session('storeInfo')['id']) {
            $this->redirect('web/index/index');
        }
        return $this->fetch();
    }
	public function register(){
		$data=input("");
		$code = $data['code'];
		$result = check_sendcode($data['mobile'], $code, '找回密码');
		if($result != 1) {
				return json(["code"=>408,"msg"=>'验证码错误或过期！']);
			
		}
    	$member = db('member')->where('mobile='.$data['mobile'])->find();
    	if($member){
    		return json(["code"=>408,"msg"=>'该手机号码已经注册']); 
   		}
		$pwd=md5_salt(substr(input('mobile'), -6));
		$res=db("member")->insertGetId(["agent_type"=>2,"mobile"=>$data['mobile'],"password"=>$pwd,"pay_password"=>$pwd]);
		if($res){
			$res2=db("mall_agent")->insert(['u_id'=>$res]);
			if($res2){
				return json(["code"=>200,"msg"=>'注册成功,初始密码为手机号码后6位数!']); 
			}
		}
		return json(["code"=>406,"msg"=> '注册失败']); 
	}
    /**
     * 登录验证
     * @return string
     */
    public function login() {
        if(request()->isPost()){
            $data   = request()->only(['login_name', 'login_pwd', 'verify', 'login_type']);
            $validate_result = $this->validate($data, 'Login');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
        		$where['mobile'] = $data['login_name'];
                $where['password'] = md5_salt($data['login_pwd']);
                $member = db('member')->where($where)->find();
				$store = db('mall_agent')->where('store_tel',$data['login_name'])->find();				
                if ($member&&$store) {
                    if ($store['store_state'] != 1) {
                        $this->error('当前用户已禁用'.$user['status'] );
                    } else {
                        session('storeInfo', $store);
						session("top_menu_id",151);
                        db('member')->update([
                        	'id'              => $member['id'],
//                          'last_login_time' => date('Y-m-d H:i:s', time()),
//                          'last_login_ip'   => $this->request->ip(),
                            'session_id'      => session_id()  //更改登录状态
                        ]);
                        $this->success('登录成功', '/web/index/index');
                    }
                } else {
                    $this->error('用户名或密码错误');
                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout() {
        session('storeInfo', null);
        $this->success('退出成功', 'web/login/index');
    }
}
